package com.jwtproject.bootserver.security.filter;


import com.jwtproject.bootserver.security.token.MyAuthenticationToken;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description：自定义登录权限拦截器
 **/
public class CustomLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public  boolean postOnly = true;

    public CustomLoginAuthenticationFilter() {
        super(new AntPathRequestMatcher("/oauth/token", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        // 授权请求
        AbstractAuthenticationToken authRequest;
        // 用户
        String principal;
        // 凭据
        String credentials;
        // 登录判断

        principal = obtainParameter(request, "username");
        credentials = obtainParameter(request, "password");
        principal = principal.trim();
        authRequest = new MyAuthenticationToken(principal, credentials);

        // 允许子类设置“details”属性
        setDetails(request, authRequest);
        AuthenticationManager authenticationManager = this.getAuthenticationManager();
        Authentication authenticate = authenticationManager.authenticate(authRequest);
        return authenticate;
    }

    private void setDetails(HttpServletRequest request,
                            AbstractAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    private String obtainParameter(HttpServletRequest request, String parameter) {
        String result =  request.getParameter(parameter);
        return result == null ? "" : result;
    }
}
